package top.riske.gen3d.util;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Enumeration;

/**
 * 请求工具类
 * created by vital on 2025/3/2 下午1:29
 */
public class RequestUtils {

    private static final Logger log = LoggerFactory.getLogger(RequestUtils.class);

    private static final String UNKNOWN = "unknown";

    /**
     * 获取请求信息
     * @param request
     * @return 类似如下的信息：ip:127.0.0.1;UserAgent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36;method:GET;url:http://127.0.0.1:8080/test;
     */
    public static String getRequestInfo(HttpServletRequest request){
        return "ip:"+getRealIp(request)
                +";UserAgent:"+getUserAgent(request)
                +";method:"+request.getMethod()
                +";url:"+getBaseUrl(request)+request.getRequestURI()
                +";"
                ;
    }

    /**
     * 获取真实ip地址
     * @param request 请求对象
     * @return ip地址，如1.1.1.1
     */
    public static String getRealIp(HttpServletRequest request){
        if (request == null) {
            return null;
        }
        // 尝试从请求头中获取客户端IP
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_X_FORWARDED_FOR",
                "HTTP_X_FORWARDED",
                "HTTP_X_CLUSTER_CLIENT_IP",
                "HTTP_CLIENT_IP",
                "HTTP_FORWARDED_FOR",
                "HTTP_FORWARDED",
                "HTTP_VIA",
                "REMOTE_ADDR"
        };

        // 遍历所有可能的头
        for (String header : headers) {
            String ip = request.getHeader(header);
            if (ip != null && !ip.isEmpty() && !UNKNOWN.equalsIgnoreCase(ip)) {
                // 处理多IP的情况
                int commaIndex = ip.indexOf(',');
                if (commaIndex > 0) {
                    ip = ip.substring(0, commaIndex);
                }
                // 返回第一个IP
                return ip;
            }
        }

        // 如果所有头部都无效，则返回远程地址
        return request.getRemoteAddr();
    }

    /**
     * 获取真实访问域名/
     * @param request 请求对象
     * @return 如https://www.example.com
     */
    public static String getBaseUrl(HttpServletRequest request){
        // 尝试从请求头中获取转发的域名和协议，处理反向代理场景
        String forwardedHost = request.getHeader("X-Forwarded-Host");
        String forwardedProto = request.getHeader("X-Forwarded-Proto");
        if (forwardedHost != null && forwardedProto != null) {
            return forwardedProto + "://" + forwardedHost;
        }

        //获取访问域名
        StringBuffer url = request.getRequestURL();
        return url.substring(0, url.indexOf("/", 8));
    }

    /**
     * 获取请求头中的User-Agent
     * @param request 请求对象
     * @return User-Agent
     */
    public static String getUserAgent(HttpServletRequest request){
        return request.getHeader("User-Agent");
    }

    /**
     * 获取所有请求头
     */
    public static String getAllHeaders(HttpServletRequest request){
        StringBuilder sb = new StringBuilder();
        for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements(); ) {
            String headerName = headerNames.nextElement();
            sb.append(headerName).append(":").append(request.getHeader(headerName)).append(";");
        }
        return sb.toString();
    }

}
